package com.diy.springframework.step;

import com.diy.springframework.step.registry.DefaultSingletonBeanRegistry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: diy_spring
 * @description:
 * @author: CaoYong
 * @create: 2021-07-24 14:01
 **/
public class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {

    private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>();

    protected Object getCachedObjectForFactory(String beanName) {
        Object object = this.factoryBeanObjectCache.get(beanName);
        return (object != null ? object : null);
    }

    protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName) throws Exception {
        if (factory.isSingleton()) {
            Object object = this.factoryBeanObjectCache.get(beanName);
            if (object == null) {
                object = doGetObjectFromFactoryBean(factory, beanName);
                this.factoryBeanObjectCache.put(beanName, (object != null ? object : null));
            }
            return (object != null ? object : null);
        } else {
            return doGetObjectFromFactoryBean(factory, beanName);
        }
    }

    private Object doGetObjectFromFactoryBean(FactoryBean factory, String name) throws Exception {
        try {
            return factory.getObject();
        }catch (Exception e) {
            throw new Exception("FactoryBean throw exception:" + name);
        }
    }
}
